package blog_service

import (
	"gin-gorm-project/modules/documents"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"sync"
	"time"
)

type BlogService struct{}

func (blogService *BlogService) QueryList(context *gin.Context) {
	blog := documents.Documents{}
	response := blog.QueryAll()
	context.JSON(http.StatusOK, gin.H{
		"data": response,
	})
}

func (blogService *BlogService) QueryByPage(context *gin.Context) {
	blog := &documents.Documents{}
	blog.Title = context.PostForm("title")
	blog.Content = context.PostForm("content")
	blog.Blurb = context.PostForm("blurb")
	pageNumber, err := strconv.Atoi(context.PostForm("pageNumber"))
	if err != nil {
		context.JSON(http.StatusInternalServerError, gin.H{
			"message": "查询出现错误，请确认翻页数据是否正确",
		})
		return
	}
	pageSize, err := strconv.Atoi(context.PostForm("pageSize"))
	if err != nil {
		context.JSON(http.StatusInternalServerError, gin.H{
			"message": "查询出现错误，请确认翻页数据是否正确",
		})
		return
	}
	response := blog.Query(pageNumber, pageSize)
	context.JSON(http.StatusOK, gin.H{
		"data": response,
	})
}

func (blogService *BlogService) QueryById(context *gin.Context) {
	id := context.Param("id")
	numId, err := strconv.Atoi(context.Param("id"))
	if len(id) == 0 || err != nil {
		context.JSON(http.StatusInternalServerError, gin.H{
			"message": "输入数据有问题",
		})
	}
	var aboutBlog documents.Documents
	aboutBlog.Id = numId
	aboutBlog.QueryById()
	context.JSON(http.StatusOK, gin.H{
		"data": aboutBlog,
	})
}

func (blogService *BlogService) Save(context *gin.Context) {
	blog := documents.Documents{}
	blog.Title = context.PostForm("title")
	blog.Content = context.PostForm("content")
	blog.Blurb = context.PostForm("blurb")
	blog.Save()
	context.JSON(http.StatusOK, gin.H{
		"message": "数据插入完成",
		"id":      blog.Id,
	})
}

func (blogService *BlogService) BuildManyDemoData(context *gin.Context) {

	var myWaitGroup sync.WaitGroup
	var saveFunc = func(documents documents.Documents) {
		documents.Save()
		myWaitGroup.Done()
	}
	blog := documents.Documents{}
	beginTime := time.Now()
	for i := 0; i < 10000; i++ {
		myWaitGroup.Add(1)
		var a = strconv.Itoa(i)
		blog.Title = "demo文章名" + a
		blog.Content = "demo文章内容" + a
		blog.Blurb = "demo文章简介" + a
		go saveFunc(blog)
	}
	myWaitGroup.Wait()
	endTime := time.Now()
	useTime := endTime.Sub(beginTime)

	context.JSON(http.StatusOK, gin.H{
		"message":  "测试数据生成成功",
		"userTime": useTime.Seconds(),
	})
}
